// Go-CapCut API 演示脚本

// 全局变量
let draftId = null;
let apiBaseUrl = window.location.origin;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化表单事件
    initForms();
    
    // 检查API服务器状态
    checkApiStatus();
});

// 初始化所有表单
function initForms() {
    // 创建草稿表单
    document.getElementById('createDraftForm').addEventListener('submit', function(e) {
        e.preventDefault();
        createDraft();
    });
    
    // 添加视频表单
    document.getElementById('addVideoForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addVideo();
    });
    
    // 添加音频表单
    document.getElementById('addAudioForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addAudio();
    });
    
    // 添加文本表单
    document.getElementById('addTextForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addText();
    });
    
    // 添加图片表单
    document.getElementById('addImageForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addImage();
    });
    
    // 保存草稿表单
    document.getElementById('saveDraftForm').addEventListener('submit', function(e) {
        e.preventDefault();
        saveDraft();
    });
}

// 检查API服务器状态
function checkApiStatus() {
    fetch(`${apiBaseUrl}/ping`)
        .then(response => response.json())
        .then(data => {
            if (data.message === 'pong') {
                showResponse('API服务器正常运行');
                enableForms(true);
            } else {
                showResponse('API服务器状态异常', true);
                enableForms(false);
            }
        })
        .catch(error => {
            showResponse(`API服务器连接失败: ${error}`, true);
            enableForms(false);
        });
}

// 启用或禁用所有表单
function enableForms(enable) {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        const inputs = form.querySelectorAll('input, button, textarea, select');
        inputs.forEach(input => {
            input.disabled = !enable;
        });
    });
    
    // 特殊处理：如果没有草稿ID，禁用除创建草稿外的所有表单
    if (enable && !draftId) {
        disableFormsExcept('createDraftForm');
    }
}

// 禁用除指定表单外的所有表单
function disableFormsExcept(formId) {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        if (form.id !== formId) {
            const inputs = form.querySelectorAll('input, button, textarea, select');
            inputs.forEach(input => {
                input.disabled = true;
            });
        }
    });
}

// 显示响应信息
function showResponse(message, isError = false) {
    const responseElement = document.getElementById('response');
    responseElement.textContent = message;
    responseElement.className = isError ? 'alert alert-danger' : 'alert alert-success';
}

// 创建草稿
function createDraft() {
    const width = document.getElementById('width').value || 1280;
    const height = document.getElementById('height').value || 720;
    const fps = document.getElementById('fps').value || 30;
    
    fetch(`${apiBaseUrl}/create_draft?width=${width}&height=${height}&fps=${fps}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                draftId = data.data.draft_id;
                showResponse(`草稿创建成功! 草稿ID: ${draftId}`);
                document.getElementById('draftIdDisplay').textContent = draftId;
                enableForms(true);
            } else {
                showResponse(`草稿创建失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}

// 添加视频
function addVideo() {
    if (!draftId) {
        showResponse('请先创建草稿', true);
        return;
    }
    
    const videoUrl = document.getElementById('videoUrl').value;
    const startTime = document.getElementById('videoStartTime').value || 0;
    const duration = document.getElementById('videoDuration').value || 0;
    
    fetch(`${apiBaseUrl}/add_video?draft_id=${draftId}&url=${encodeURIComponent(videoUrl)}&start_time=${startTime}&duration=${duration}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                showResponse(`视频添加成功! 片段ID: ${data.data.segment_id}`);
            } else {
                showResponse(`视频添加失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}

// 添加音频
function addAudio() {
    if (!draftId) {
        showResponse('请先创建草稿', true);
        return;
    }
    
    const audioUrl = document.getElementById('audioUrl').value;
    const startTime = document.getElementById('audioStartTime').value || 0;
    const duration = document.getElementById('audioDuration').value || 0;
    const volume = document.getElementById('audioVolume').value || 100;
    
    fetch(`${apiBaseUrl}/add_audio?draft_id=${draftId}&url=${encodeURIComponent(audioUrl)}&start_time=${startTime}&duration=${duration}&volume=${volume}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                showResponse(`音频添加成功! 片段ID: ${data.data.segment_id}`);
            } else {
                showResponse(`音频添加失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}

// 添加文本
function addText() {
    if (!draftId) {
        showResponse('请先创建草稿', true);
        return;
    }
    
    const text = document.getElementById('text').value;
    const startTime = document.getElementById('textStartTime').value || 0;
    const duration = document.getElementById('textDuration').value || 5;
    const x = document.getElementById('textX').value || 0.5;
    const y = document.getElementById('textY').value || 0.5;
    const fontSize = document.getElementById('fontSize').value || 30;
    const color = document.getElementById('textColor').value || '#FFFFFF';
    
    fetch(`${apiBaseUrl}/add_text?draft_id=${draftId}&text=${encodeURIComponent(text)}&start_time=${startTime}&duration=${duration}&x=${x}&y=${y}&font_size=${fontSize}&color=${encodeURIComponent(color)}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                showResponse(`文本添加成功! 片段ID: ${data.data.segment_id}`);
            } else {
                showResponse(`文本添加失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}

// 添加图片
function addImage() {
    if (!draftId) {
        showResponse('请先创建草稿', true);
        return;
    }
    
    const imageUrl = document.getElementById('imageUrl').value;
    const startTime = document.getElementById('imageStartTime').value || 0;
    const duration = document.getElementById('imageDuration').value || 5;
    const x = document.getElementById('imageX').value || 0.5;
    const y = document.getElementById('imageY').value || 0.5;
    const width = document.getElementById('imageWidth').value || 0.3;
    const height = document.getElementById('imageHeight').value || 0.3;
    
    fetch(`${apiBaseUrl}/add_image?draft_id=${draftId}&url=${encodeURIComponent(imageUrl)}&start_time=${startTime}&duration=${duration}&x=${x}&y=${y}&width=${width}&height=${height}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                showResponse(`图片添加成功! 片段ID: ${data.data.segment_id}`);
            } else {
                showResponse(`图片添加失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}

// 保存草稿
function saveDraft() {
    if (!draftId) {
        showResponse('请先创建草稿', true);
        return;
    }
    
    fetch(`${apiBaseUrl}/save_draft?draft_id=${draftId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 0) {
                const draftUrl = data.data.draft_url;
                showResponse(`草稿保存成功! 草稿URL: ${draftUrl}`);
                
                // 创建下载链接
                const downloadLink = document.createElement('a');
                downloadLink.href = draftUrl;
                downloadLink.className = 'btn btn-success mt-3';
                downloadLink.textContent = '下载草稿';
                downloadLink.target = '_blank';
                
                const responseElement = document.getElementById('response');
                responseElement.appendChild(document.createElement('br'));
                responseElement.appendChild(document.createElement('br'));
                responseElement.appendChild(downloadLink);
            } else {
                showResponse(`草稿保存失败: ${data.message}`, true);
            }
        })
        .catch(error => {
            showResponse(`请求错误: ${error}`, true);
        });
}
